﻿namespace Numbrella.TaskSamples.SecurityViolations
{
	using System;
	using System.IO;
	using System.Reflection;
	using System.Security;
	using System.Windows.Forms;
	using Microsoft.Win32;
	using Numbrella.Core;
	
	[Serializable]
	public class Task : TaskBase<bool>
	{
		public Task(int id)
			: base(id)
		{
		}

		protected override bool ReallyPerform()
		{
			try
			{
				switch (this.Id)
				{
					case 0:
						ShowUI();
						break;
					case 1:
						AccessRegistry();
						break;
					case 2:
						PerformReflection();
						break;
					case 3:
						AccessFilesystem();
						break;
					case 4:
						AccessEnvironment();
						break;
				}

				return true;
			}
			catch (SecurityException)
			{
			    return false;
			}
			catch (FieldAccessException)
			{
			    return false;
			}
		}

		private static void ShowUI()
		{
			Form gandalf = new Form();
			gandalf.Show();
			gandalf.Close();
		}

		private static void AccessRegistry()
		{
			Registry.CurrentUser.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\InstallRoot", "nazgul");
			Registry.CurrentUser.CreateSubKey("karaul");
		}

		private static void PerformReflection()
		{
			MagicKingdom gondor = new MagicKingdom();
			FieldInfo bilbo = typeof(MagicKingdom).GetField("princess", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			bilbo.SetValue(gondor, 69);
		}

		private static void AccessFilesystem()
		{
			File.WriteAllText("./Message.txt", "magic sword");
			File.ReadAllText("./Message.txt");
		}

		private static void AccessEnvironment()
		{
			Environment.CurrentDirectory = @"C:\";
			Environment.GetEnvironmentVariable("path");
		}
	}
}